﻿/* $RCSFile: PageStripDetailList.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Configuration/Settings/PageStripDetailList.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:27  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Caching;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.Configuration;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.Security;

using Cache2    =   AddonNice.Settings.Cache.CurrentCache;
using Key2      =   AddonNice.Settings.Cache.Key;


namespace AddonNice.Configuration.Settings
{
    public class PageStripDetailsList : List<PageStripDetails> 
    {
        public bool    initialized     =   false;

        PortalSettings _portalSettings; 
        protected PortalSettings portalSettings 
        {
            get 
            {
                if ( _portalSettings == null )
                    _portalSettings = (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
                return _portalSettings;
            }
        }

        /// <summary>
        /// Basic Ctor, nothing initialized
        /// </summary>
        public PageStripDetailsList()
        { }

        /// <summary>
        /// This Ctor loads data dierctly from DB
        /// </summary>
        public PageStripDetailsList(int portalID,string CurrentLayout)
        {
            SqlDataReader result    =   null;
            try
            {
                result              =   new PagesDB().GetAllPortalPages(portalID);
                initialized         =   ReadData(result,CurrentLayout,false);
            }
            catch (Exception ex)
            {
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PageStripDetailsList Ctor PortalID: {0}, ex: {1}", portalID, ex), SettingsTraceSwitch.Sw.Info);
            }
            finally
            {
                if (result != null)
                    result.Close();
            }
        }

        /// <summary>
        /// This Ctor reads data from datareader passed as parameter, this datareader should have same format as PagesDB().GetAllPortalPages
        /// </summary>
        public PageStripDetailsList(SqlDataReader result,string CurrentLayout)
        { 
            try
            {
                initialized     =   ReadData(result,CurrentLayout,false);
            }
            catch (Exception ex)
            {
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PageStripDetailsList Ctor with SqlDataReader ex: {0}",ex), SettingsTraceSwitch.Sw.Info);
            }
        }

        public bool ReadData(SqlDataReader result,string CurrentLayout,bool isPageItem)
        { 
            if ( SettingsTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageStripDetailsList ReadData BEG CurrentLayout: '{0}', isPageItem: {1}.", 
                    CurrentLayout,isPageItem),SettingsTraceSwitch.Sw.Info);
            bool ret                                    =   false;
			try
			{
				// Read the first resultset -- Desktop Tab Information
				while (result.Read())
				{
                    PageStripDetails tabDetails         =   (isPageItem) ? new PageItem(): new PageStripDetails();
					tabDetails.PageID                   =   (int)result[StStr.DBPageID];
                    tabDetails.PortalID                 =   (int)result[StStr.DBPortalID];
					tabDetails.ParentPageID             =    Convert.IsDBNull(result[StStr.DBParentPageID]) ? 0 : (int)result[StStr.DBParentPageID];
					tabDetails.PageName                 =   (string)result[StStr.DBPageName];
					tabDetails.PageTitle                =   (string)result[StStr.DBPageTitle];
					tabDetails.PageKeyPhrase            =   (string)result[StStr.DBPageKeyPhrase];
                    tabDetails.PageImage                =   result[StStr.DBPageSkin].ToString().Trim();
					tabDetails.PageOrder                =   (int)result[StStr.DBPageOrder];
					tabDetails.PageLayout               =   CurrentLayout;
                    if ( result[StStr.DBPageLayout] != DBNull.Value )
                        tabDetails.Flags                =   (ADNPageFlags)result[StStr.DBPageLayout];
					tabDetails.AuthorizedRoles          =   (string)result[StStr.DBAuthRoles];
                    if ( result[StStr.DBUrlName] != DBNull.Value )
					    tabDetails.UrlName              =   (string)result[StStr.DBUrlName];
                    tabDetails.nbModules                =   (int)result[StStr.DBPageNbModules];
                    if ( isPageItem ) 
                        ((PageItem)tabDetails).NestLevel=   (int)result[StStr.DBNestLevel];
					Add(tabDetails);
                    if ( SettingsTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]PageStripDetailsList ReadData pageID: {0}, PortalID: {1}, PageName: {2}, PageOrder: {3}.", 
                            new object[] { tabDetails.PageID, tabDetails.PortalID, tabDetails.PageName, tabDetails.PageOrder }),SettingsTraceSwitch.Sw.Info);
				}
				ret			                            =	true;
			}
			catch (Exception ex)
			{
				if ( SettingsTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PageStripDetailsList ReadData ex: {0}", ex),SettingsTraceSwitch.Sw.Info);
				ret	                                    =	false;
			}
            return ret;
        }

        /// <summary>
        /// Portal has changed its global default layout, propagate the change
        /// </summary>
        /// <param name="CurrentLayout"></param>
        public void ResetLayouts(string CurrentLayout)
        {
            foreach(PageStripDetails tabDetails in this)
                tabDetails.PageLayout   =   CurrentLayout;
        }

        public bool GetPagesFlat(int portalID)
        {
            SqlDataReader result        =   null;
            try
            {
                result                  =   new PagesDB().GetPagesFlat(portalID);
                initialized             =   ReadData(result,string.Empty,true);
            }
            catch (Exception ex)
            {
                if (SettingsTraceSwitch.Sw.TraceError)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]PageStripDetailsList Ctor PortalID: {0}, ex: {1}", portalID, ex), SettingsTraceSwitch.Sw.Info);
            }
            finally
            {
                if (result != null)
                    result.Close();
            }
            return initialized;
        }
    
    
    }

    /// <summary>
    /// Specialized collection for menus
    /// List of all authorized PageStrip detail from existing pages for the current portail
    /// </summary>
    public class AuthorizedPageStripDetail: PageStripDetailsList
    {

        BindOption Bind                 =   BindOption.BindOptionNone;
        
        public int ParentPageID         =   -1;
        public int CurrentParentPageID  =   -1;
        
        /// <summary>
        /// Populates with list of pages based on binding option selected.
		/// </summary>
        public AuthorizedPageStripDetail(BindOption Bd,int wParentPageID,int wCurrentParentPageID) : base()
		{
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor BindOption: {0}, wParentPageID: {1}, wCurrentParentPageID: {2}", 
                    Bd,wParentPageID,wCurrentParentPageID),NavTraceSwitch.Sw.Info);
            if ( HttpContext.Current == null)
                return;
            Bind                    =   Bd;
            CurrentParentPageID     =   wCurrentParentPageID;
            ParentPageID            =   wParentPageID;

            string CKey             =   string.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}",
                new object[] {
                    StStr.AuthorizedPageStripDetail,
                    PortalSecurity.Wrapper.userId,
                    Bind,
                    CurrentParentPageID,
                    ParentPageID,
                    Config.UrlPort,
                    portalSettings.PortalContentLanguage,
                    portalSettings.PortalID
                }
                );

            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor CKey: {0}",CKey),NavTraceSwitch.Sw.Info);
            if ( Cache2.Exists(CKey))
            {
                if ( NavTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor found in cache ckey: {0}", CKey),NavTraceSwitch.Sw.Info);
                AddRange((AuthorizedPageStripDetail)Cache2.Get(CKey));
                return;
            }
 
            try
            {
                switch (Bind)
                {
                    case BindOption.BindOptionTop:
                        {
                            if ( NavTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor GetTabs 0, ActivePage.PageID: {0}",portalSettings.ActivePageSettings.PageID),NavTraceSwitch.Sw.Info);
                            if ( CurrentParentPageID == -1 )
                                CurrentParentPageID =   0;
                            break;
                        }

                    case BindOption.BindOptionCurrentChilds:
                        {
                            if ( CurrentParentPageID == -1 )
                                CurrentParentPageID  = PortalSettings.GetRootPage(portalSettings.ActivePageSettings, portalSettings.DesktopPages).PageID;
                            if ( NavTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor GetTabs CurrentParentPageID : {0}, ActivePage.PageID: {1}",CurrentParentPageID ,portalSettings.ActivePageSettings.PageID),NavTraceSwitch.Sw.Info);
                            break;
                        }

                    case BindOption.BindOptionSubtabSibling:
                    case BindOption.BindOptionSiblings:
                        {
                            if (CurrentParentPageID == -1)
                            {
                                if (portalSettings.ActivePageSettings.ParentPageID == StStr.PageIDNotAssigned )
                                    CurrentParentPageID  = portalSettings.ActivePageSettings.PageID;
                                else
                                    CurrentParentPageID  = portalSettings.ActivePageSettings.ParentPageID;
                            }
                            if ( NavTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor GetTabs currentTabRoot: {0}, ActivePage.PageID: {1}",CurrentParentPageID ,portalSettings.ActivePageSettings.PageID),NavTraceSwitch.Sw.Info);
                            break;
                        }

                    case BindOption.BindOptionTabSibling:
                    case BindOption.BindOptionChildren:
                        {
                            if (CurrentParentPageID == -1)
                                CurrentParentPageID =   portalSettings.ActivePageSettings.PageID;
                            if ( NavTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail Ctor GetTabs currentTabRoot: {0}, ActivePage.PageID: {0}",portalSettings.ActivePageSettings.PageID),NavTraceSwitch.Sw.Info);
                            break;
                        }

                    case BindOption.BindOptionDefinedParent:
                        if (ParentPageID == -1)
                        {
                            string msg  =   string.Format("[E]AuthorizedPageStripDetail Ctor bind option BindOptionDefinedParent and no ParentPageID: {0}", Bind);
                            if ( NavTraceSwitch.Sw.TraceError )
                                Trace.WriteLine( msg,NavTraceSwitch.Sw.Info);
                            throw new Exception(msg);
                        }
                        break;
                    default:
                        {
                            string msg  =   string.Format("[E]AuthorizedPageStripDetail Ctor unknown bind option : {0}", Bind);
                            if ( NavTraceSwitch.Sw.TraceError )
                                Trace.WriteLine( msg,NavTraceSwitch.Sw.Info);
                            throw new Exception(msg);
                        }
                }
                GetTabs(CurrentParentPageID, portalSettings.DesktopPages);

                // insert result in cache making a dependancy on pages architecture
                Cache2.InsertVLong(CKey,this,Cache2.GlobalPagesDependency());
            }
            catch (Exception ex)
            {
                if ( NavTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]AuthorizedPageStripDetail Bind: {0}, CurrentParentPageID: {1}, InitDataSource ex: {2}", Bind,CurrentParentPageID,ex),NavTraceSwitch.Sw.Info);
                throw;
            }
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( "[V]AuthorizedPageStripDetail InitDataSource END.",NavTraceSwitch.Sw.Info);
		}


        private void GetTabs(int parentID, PageStripDetailsList Tabs)
		{
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail GetTabs BEG parentID: {0}, Count: {1}", parentID,Tabs.Count),NavTraceSwitch.Sw.Info);
 
            bool isForm             =   (Config.AuthenticationMode == System.Web.Configuration.AuthenticationMode.Forms );
			// Populate Tab List with authorized tabs
			for (int i=0; i < Tabs.Count; i++)
			{
				PageStripDetails tab =  Tabs[i];
                if ( NavTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail GetTabs tab.PageName: {0}, ParentPageID: {1}, parentID: {2}", 
                        new object[] { tab.PageName, tab.ParentPageID, parentID }),NavTraceSwitch.Sw.Info);

				if ( tab.OkForMenus && 
                    ( isForm || 
                    ( !isForm && !tab.FormsOnly ) ) && 
                    (tab.ParentPageID == parentID) ) // Get selected row only
				{
					if (PortalSecurity.IsUserInRoles(tab.AuthorizedRoles))
					{
                        if ( NavTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail GetTabs authorizedTabs.Add tab.PageName: {0}, PageID: {1}", tab.PageName, tab.PageID),NavTraceSwitch.Sw.Info);
                        Add(tab);
					}
				}
			}
            if ( NavTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]AuthorizedPageStripDetail GetTabs END Count: {0}",Count),NavTraceSwitch.Sw.Info);

		}
	} 
}